package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.common.PageResult;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxCustomerList;
import com.adk.backend.mapper.YwListMapper;
import com.adk.backend.service.CustomerService;
import com.adk.backend.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/customer")
public class CustomerController {
    
    @Autowired
    private CustomerService customerService;
    
    @Autowired
    private LogUtil logUtil;
    
    @Autowired
    private YwListMapper ywListMapper;
    
    @Autowired
    private com.adk.backend.mapper.AdminMapper adminMapper;
    
    @Autowired
    private com.adk.backend.mapper.AttrMapper attrMapper;
    
    /**
     * 分页查询客户列表
     */
    @RequiresPermission("view")
    @GetMapping("/list")
    public Result<PageResult<LxCustomerList>> getCustomerList(
            @RequestParam(required = false) String cusCode,
            @RequestParam(required = false) String cusShort,
            @RequestParam(required = false) String companyName,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long staff,
            @RequestParam(required = false) Integer type,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        Map<String, Object> params = new HashMap<>();
        params.put("cusCode", cusCode);
        params.put("cusShort", cusShort);
        params.put("companyName", companyName);
        params.put("status", status);
        params.put("staff", staff);
        params.put("type", type);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        
        PageResult<LxCustomerList> result = customerService.getCustomerList(params);
        return Result.success(result);
    }
    
    /**
     * 根据客户代码查询客户
     */
    @RequiresPermission("view")
    @GetMapping("/detail")
    public Result<LxCustomerList> getCustomerDetail(@RequestParam String cusCode) {
        LxCustomerList customer = customerService.getCustomerByCode(cusCode);
        if (customer != null) {
            return Result.success(customer);
        }
        return Result.error("客户不存在");
    }
    
    /**
     * 创建客户
     */
    @RequiresPermission("edit")
    @PostMapping("/create")
    public Result<LxCustomerList> createCustomer(@RequestBody LxCustomerList customer, HttpServletRequest request) {
        try {
            // 设置add_uid（从请求中获取用户ID）
            Long userId = (Long) request.getAttribute("userId");
            if (userId != null) {
                customer.setAddUid(userId.intValue());
            }
            
            LxCustomerList result = customerService.createCustomer(customer);
            
            // 记录操作日志
            if (userId != null) {
                logUtil.logAction(userId, "customer_list", result.getId(), "Insert客户");
            }
            
            return Result.success("Success.", result);
        } catch (RuntimeException e) {
            log.error("创建客户失败", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建客户失败", e);
            return Result.error("创建客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新客户
     */
    @RequiresPermission("edit")
    @PostMapping("/update")
    public Result<Boolean> updateCustomer(@RequestBody LxCustomerList customer, HttpServletRequest request) {
        try {
            boolean result = customerService.updateCustomer(customer);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                if (userId != null) {
                    logUtil.logAction(userId, "customer_list", customer.getId(), "Update客户信息");
                }
                return Result.success("Success.", true);
            }
            return Result.error("Data Error");
        } catch (RuntimeException e) {
            log.error("更新客户失败", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新客户失败", e);
            return Result.error("更新客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除客户（逻辑删除）
     */
    @RequiresPermission("del")
    @PostMapping("/delete")
    public Result<Boolean> deleteCustomer(@RequestParam Long id, HttpServletRequest request) {
        try {
            LxCustomerList customer = customerService.getById(id);
            if (customer != null) {
                customer.setStatus(0); // 禁用
                boolean result = customerService.updateById(customer);
                if (result) {
                    // 记录操作日志
                    Long userId = (Long) request.getAttribute("userId");
                    if (userId != null) {
                        logUtil.logAction(userId, "customer_list", id, "删除客户");
                    }
                    return Result.success("删除成功", true);
                }
            }
            return Result.error("客户删除失败");
        } catch (Exception e) {
            log.error("删除客户失败", e);
            return Result.error("删除客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有启用的客户列表（用于下拉选择）
     */
    @RequiresPermission("view")
    @GetMapping("/all")
    public Result<java.util.List<LxCustomerList>> getAllEnabledCustomers() {
        try {
            java.util.List<LxCustomerList> customers = customerService.getAllEnabledCustomers();
            return Result.success(customers);
        } catch (Exception e) {
            log.error("获取客户列表失败", e);
            return Result.error("获取客户列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取开发列表（用于客户管理中的开发选择）
     */
    @RequiresPermission("view")
    @GetMapping("/yw-list")
    public Result<java.util.List<java.util.Map<String, Object>>> getYwList() {
        try {
            // 查询开发列表（is_show=1）
            java.util.List<com.adk.backend.entity.LxYwList> ywList = ywListMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxYwList>()
                    .eq("is_show", 1)
                    .orderByAsc("yw_user")
            );
            
            java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
            for (com.adk.backend.entity.LxYwList yw : ywList) {
                java.util.Map<String, Object> map = new java.util.HashMap<>();
                map.put("id", yw.getId());
                map.put("username", yw.getYwUser());
                result.add(map);
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取开发列表失败", e);
            return Result.error("获取开发列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 客户转移
     */
    @RequiresPermission("transfer")
    @PostMapping("/transfer")
    public Result<Boolean> transferCustomer(@RequestParam Long id, @RequestParam Long newId, HttpServletRequest request) {
        try {
            boolean result = customerService.transferCustomer(id, newId);
            if (result) {
                Long userId = (Long) request.getAttribute("userId");
                if (userId != null) {
                    logUtil.logAction(userId, "customer_list", id, "客户转移");
                }
                return Result.success("客户转移成功", true);
            }
            return Result.error("客户转移失败");
        } catch (Exception e) {
            log.error("客户转移失败", e);
            return Result.error("客户转移失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新客户开发/跟单
     */
    @RequiresPermission("yw")
    @PostMapping("/yw")
    public Result<Boolean> updateCustomerYw(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long id = convertToLong(params.get("id"));
            Long ywId = convertToLong(params.get("ywId"));
            Integer type = (Integer) params.get("type");
            String ywDate = (String) params.get("ywDate");
            
            if (id == null || id <= 0) {
                return Result.error("客户ID不能为空");
            }
            if (ywId == null || ywId <= 0) {
                return Result.error("业务员ID不能为空");
            }
            if (type == null || (type != 1 && type != 2)) {
                return Result.error("类型错误：1-开发，2-跟单");
            }
            
            boolean result = customerService.updateCustomerYw(id, ywId, type, ywDate);
            if (result) {
                Long userId = (Long) request.getAttribute("userId");
                if (userId != null) {
                    logUtil.logAction(userId, "customer_list", id, "更新客户开发/跟单");
                }
                return Result.success("更新成功", true);
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新客户开发/跟单失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新客户账期
     */
    @RequiresPermission("pt")
    @PostMapping("/pt")
    public Result<Boolean> updateCustomerPt(@RequestParam Long id, @RequestParam Integer pt, HttpServletRequest request) {
        try {
            if (id == null || id <= 0) {
                return Result.error("客户ID不能为空");
            }
            if (pt == null || pt < 0 || pt > 2) {
                return Result.error("账期错误：0-票结，1-半月结，2-月结");
            }
            
            boolean result = customerService.updateCustomerPt(id, pt);
            if (result) {
                Long userId = (Long) request.getAttribute("userId");
                if (userId != null) {
                    logUtil.logAction(userId, "customer_list", id, "更新客户账期");
                }
                return Result.success("更新成功", true);
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新客户账期失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新客户合同
     */
    @RequiresPermission("contract")
    @PostMapping("/contract")
    public Result<Boolean> updateCustomerContract(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long id = convertToLong(params.get("id"));
            if (id == null || id <= 0) {
                return Result.error("客户ID不能为空");
            }
            
            boolean result = customerService.updateCustomerContract(id, params);
            if (result) {
                Long userId = (Long) request.getAttribute("userId");
                if (userId != null) {
                    logUtil.logAction(userId, "customer_list", id, "更新客户合同");
                }
                return Result.success("更新成功", true);
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新客户合同失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取客户账号列表
     */
    @RequiresPermission("view")
    @GetMapping("/users")
    public Result<java.util.List<com.adk.backend.entity.LxAdmin>> getCustomerUsers(@RequestParam Long customerId) {
        try {
            if (customerId == null || customerId <= 0) {
                return Result.error("客户ID不能为空");
            }
            
            java.util.List<com.adk.backend.entity.LxAdmin> users = adminMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxAdmin>()
                    .eq("user_type", 13)
                    .eq("customer_id", customerId)
                    .orderByDesc("add_time")
            );
            
            return Result.success(users);
        } catch (Exception e) {
            log.error("获取客户账号列表失败", e);
            return Result.error("获取客户账号列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加客户账号
     */
    @RequiresPermission("edit")
    @PostMapping("/users/add")
    public Result<Boolean> addCustomerUser(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long customerId = convertToLong(params.get("customerId"));
            String email = (String) params.get("email");
            String password = (String) params.get("password");
            String username = (String) params.get("username");
            
            if (customerId == null || customerId <= 0) {
                return Result.error("客户ID不能为空");
            }
            if (email == null || email.trim().isEmpty()) {
                return Result.error("邮箱不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            // 检查邮箱是否已存在
            com.adk.backend.entity.LxAdmin existUser = adminMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxAdmin>()
                    .eq("email", email)
            );
            if (existUser != null) {
                return Result.error("邮箱已存在");
            }
            
            // 创建账号
            com.adk.backend.entity.LxAdmin admin = new com.adk.backend.entity.LxAdmin();
            admin.setEmail(email);
            admin.setUsername(username != null ? username : email);
            admin.setAdminuser(email);
            // 密码加密（MD5）
            String passwordKey = "bm"; // 从配置读取
            admin.setAdminpwd(org.springframework.util.DigestUtils.md5DigestAsHex((passwordKey + password).getBytes()));
            admin.setUserType(13);
            admin.setCustomerId(customerId);
            admin.setStatus(0); // 0-正常
            admin.setAddTime((int) (System.currentTimeMillis() / 1000));
            
            boolean result = adminMapper.insert(admin) > 0;
            if (result) {
                Long userId = (Long) request.getAttribute("userId");
                if (userId != null) {
                    logUtil.logAction(userId, "admin", admin.getId(), "添加客户账号");
                }
                return Result.success("添加成功", true);
            }
            return Result.error("添加失败");
        } catch (Exception e) {
            log.error("添加客户账号失败", e);
            return Result.error("添加客户账号失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新客户账号
     */
    @RequiresPermission("edit")
    @PostMapping("/users/update")
    public Result<Boolean> updateCustomerUser(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long id = convertToLong(params.get("id"));
            String email = (String) params.get("email");
            String password = (String) params.get("password");
            String username = (String) params.get("username");
            Integer status = (Integer) params.get("status");
            
            if (id == null || id <= 0) {
                return Result.error("账号ID不能为空");
            }
            
            com.adk.backend.entity.LxAdmin admin = adminMapper.selectById(id);
            if (admin == null || admin.getUserType() == null || admin.getUserType() != 13) {
                return Result.error("账号不存在或不是客户账号");
            }
            
            // 如果修改邮箱，检查是否已存在
            if (email != null && !email.trim().isEmpty() && !email.equals(admin.getEmail())) {
                com.adk.backend.entity.LxAdmin existUser = adminMapper.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxAdmin>()
                        .eq("email", email)
                        .ne("id", id)
                );
                if (existUser != null) {
                    return Result.error("邮箱已存在");
                }
                admin.setEmail(email);
                admin.setAdminuser(email);
            }
            
            if (username != null && !username.trim().isEmpty()) {
                admin.setUsername(username);
            }
            
            if (password != null && !password.trim().isEmpty()) {
                String passwordKey = "bm";
                admin.setAdminpwd(org.springframework.util.DigestUtils.md5DigestAsHex((passwordKey + password).getBytes()));
            }
            
            if (status != null) {
                admin.setStatus(status);
            }
            
            admin.setUpdateTime((int) (System.currentTimeMillis() / 1000));
            
            boolean result = adminMapper.updateById(admin) > 0;
            if (result) {
                Long userId = (Long) request.getAttribute("userId");
                if (userId != null) {
                    logUtil.logAction(userId, "admin", id, "更新客户账号");
                }
                return Result.success("更新成功", true);
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新客户账号失败", e);
            return Result.error("更新客户账号失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除客户账号
     */
    @RequiresPermission("edit")
    @PostMapping("/users/delete")
    public Result<Boolean> deleteCustomerUser(@RequestParam Long id, HttpServletRequest request) {
        try {
            if (id == null || id <= 0) {
                return Result.error("账号ID不能为空");
            }
            
            com.adk.backend.entity.LxAdmin admin = adminMapper.selectById(id);
            if (admin == null || admin.getUserType() == null || admin.getUserType() != 13) {
                return Result.error("账号不存在或不是客户账号");
            }
            
            boolean result = adminMapper.deleteById(id) > 0;
            if (result) {
                Long userId = (Long) request.getAttribute("userId");
                if (userId != null) {
                    logUtil.logAction(userId, "admin", id, "删除客户账号");
                }
                return Result.success("删除成功", true);
            }
            return Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除客户账号失败", e);
            return Result.error("删除客户账号失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取客户证件
     */
    @RequiresPermission("view")
    @GetMapping("/id-document")
    public Result<String> getCustomerIdDocument(@RequestParam Long customerId) {
        try {
            if (customerId == null || customerId <= 0) {
                return Result.error("客户ID不能为空");
            }
            
            // 查询客户证件（type=1, tb_name='customer_list', tb_id=customerId）
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxAttr> wrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            wrapper.eq("type", 1)
                   .eq("tb_name", "customer_list")
                   .eq("tb_id", customerId)
                   .orderByDesc("id")
                   .last("LIMIT 1");
            
            com.adk.backend.entity.LxAttr attr = attrMapper.selectOne(wrapper);
            if (attr != null && attr.getAttr() != null && !attr.getAttr().trim().isEmpty()) {
                return Result.success(attr.getAttr());
            }
            return Result.error("客户证件不存在");
        } catch (Exception e) {
            log.error("获取客户证件失败", e);
            return Result.error("获取客户证件失败：" + e.getMessage());
        }
    }
    
    /**
     * 文件预览/下载接口（客户证件）
     */
    @RequiresPermission("view")
    @GetMapping("/file")
    public org.springframework.http.ResponseEntity<org.springframework.core.io.Resource> previewOrDownloadCustomerFile(
            @RequestParam String filePath,
            @RequestParam(required = false, defaultValue = "false") Boolean download) {
        try {
            // 验证文件路径是否合法（防止路径遍历攻击）
            String cleanPath = filePath.startsWith("./") ? filePath.substring(2) : filePath;
            if (cleanPath.contains("..") || !cleanPath.startsWith("customer/")) {
                return org.springframework.http.ResponseEntity.badRequest().build();
            }
            
            // 构建完整文件路径
            String fullPath = "uploads/" + cleanPath;
            java.io.File file = new java.io.File(fullPath);
            if (!file.exists() || !file.isFile()) {
                return org.springframework.http.ResponseEntity.notFound().build();
            }
            
            org.springframework.core.io.Resource resource = new org.springframework.core.io.FileSystemResource(file);
            String fileName = file.getName();
            
            // 根据文件扩展名确定Content-Type
            String contentType = "application/octet-stream";
            String lowerFileName = fileName.toLowerCase();
            if (lowerFileName.endsWith(".jpg") || lowerFileName.endsWith(".jpeg")) {
                contentType = "image/jpeg";
            } else if (lowerFileName.endsWith(".png")) {
                contentType = "image/png";
            } else if (lowerFileName.endsWith(".pdf")) {
                contentType = "application/pdf";
            } else if (lowerFileName.endsWith(".jfif")) {
                contentType = "image/jpeg";
            }
            
            org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
            if (download) {
                headers.setContentDispositionFormData("attachment", fileName);
            } else {
                headers.setContentDispositionFormData("inline", fileName);
            }
            headers.setContentType(org.springframework.http.MediaType.parseMediaType(contentType));
            
            return org.springframework.http.ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            log.error("文件预览/下载失败", e);
            return org.springframework.http.ResponseEntity.status(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 辅助方法：将对象安全地转换为 Long 类型
     */
    private Long convertToLong(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof Long) {
            return (Long) obj;
        }
        if (obj instanceof Integer) {
            return ((Integer) obj).longValue();
        }
        if (obj instanceof Number) {
            return ((Number) obj).longValue();
        }
        try {
            return Long.parseLong(obj.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }
}

